package com.ding.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁（写锁）一次只能一个线程占有
 * 共享锁（读锁） 多个线程可以同时占有
 * @author ding
 * @date 2021/7/18 10:07
 */


public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }).start();
        }

        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }).start();
        }
    }

}

/**
 *加锁
 */
class MyCacheLock {
    private volatile Map<String, Object> map = new HashMap<>();

    //读写锁： 更加细粒度的控制
    ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 写入的时候只希望同事只有一个线程写
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        lock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "开始写");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }


    public Object get(String key) {
        lock.readLock().lock();
        Object o = null;
        try {
            System.out.println(Thread.currentThread().getName() + "开始读");
            o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return o;

    }
}

/**
 * 自定义缓存
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();


    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "开始写");
        map.put(key, value);

        System.out.println(Thread.currentThread().getName() + "写入完成");
    }


    public Object get(String key) {
        System.out.println(Thread.currentThread().getName() + "开始读");

        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取成功");
        return o;

    }
}
